package com.holyn.guofang.view.my;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.CardOrderDetailWo;
import com.holyn.guofang.model.webhttp.wo.PaySignWo;
import com.holyn.guofang.model.webhttp.wo.StatusWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.my.MyContract;
import com.holyn.guofang.presenter.my.MyPresenter;
import com.holyn.guofang.utils.HtmlUtil;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.dialog.ToastDialog;
import com.vondear.rxtools.interfaces.onRequestListener;
import com.vondear.rxtools.model.alipay.AliPayModel;
import com.vondear.rxtools.model.alipay.AliPayOrderInfoUtil;
import com.vondear.rxtools.model.alipay.AliPayTools;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/8/29.
 */

public class MyOrderDetailActivity extends BaseActivity implements BaseView, MyContract.OrderDetailView{
    private static final int REQUEST_ACTION_POST_CARD_ORDER_DETAIL= 0x0001;
    private static final int REQUEST_ACTION_POST_DELETE_ORDER= 0x0002;
    private static final int REQUEST_ACTION_POST_UPDATE_OFFLINE_PAY_STATUS= 0x0003;//线下
    private static final int REQUEST_ACTION_POST_UPDATE_ORDER_PAY_STATUS= 0x0004;//线上
    private static final int REQUEST_ACTION_POST_ALIPAY_SIGN= 0x0005;//线上


    public static final String INTENT_KEY_FROM_ACTIVITY_NAME = "INTENT_KEY_FROM_ACTIVITY_NAME";
    private static final String INTENT_KEY_ORDER_ID = "INTENT_KEY_ORDER_ID";
    public static final String INTENT_KEY_IS_NEED_REFLASH = "INTENT_KEY_IS_NEED_REFLASH";

    @BindView(R.id.ll_user_card)
    LinearLayout llUserCard;
    @BindView(R.id.iv_user_card)
    ImageView ivUserCard;
    @BindView(R.id.tv_user_card_name_above_image)
    TextView tvUserCardNameAboveImage;
    @BindView(R.id.tv_user_card_price_above_image)
    TextView tvUserCardPriceAboveImage;
    @BindView(R.id.tv_user_card_name)
    TextView tvUserCardName;
    @BindView(R.id.tv_user_card_price)
    TextView tvUserCardPrice;
    @BindView(R.id.ll_attached_card)
    LinearLayout llAttachedCard;
    @BindView(R.id.iv_attached_card)
    ImageView ivAttachedCard;
    @BindView(R.id.tv_attached_card_name_above_image)
    TextView tvAttachedCardNameAboveImage;
    @BindView(R.id.tv_attached_card_price_above_image)
    TextView tvAttachedCardPriceAboveImage;
    @BindView(R.id.tv_attached_card_name)
    TextView tvAttachedCardName;
    @BindView(R.id.tv_attached_card_count)
    TextView tvAttachedCardCount;
    @BindView(R.id.tv_attached_card_price)
    TextView tvAttachedCardPrice;
    @BindView(R.id.ll_coupon_card)
    LinearLayout llCouponCard;
    @BindView(R.id.iv_coupon_card)
    ImageView ivCouponCard;
    @BindView(R.id.tv_coupon_card_name_above_image)
    TextView tvCouponCardNameAboveImage;
    @BindView(R.id.tv_coupon_card_rate)
    TextView tvCouponCardRate;
    @BindView(R.id.tv_all_sum_price)
    TextView tvAllSumPrice;
    @BindView(R.id.tv_minus_sum_price)
    TextView tvMinusSumPrice;
    @BindView(R.id.tv_actual_sum_price)
    TextView tvActualSumPrice;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_pay_currency)
    TextView tvPayCurrency;
    @BindView(R.id.tv_pay_way)
    TextView tvPayWay;
    @BindView(R.id.tv_offline_pay)
    TextView tvOfflinePay;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private int fromActivityStatus = -1;//1-代表来自国方购卡页面，2-代表来自订单列表
    private Integer orderId;

    MyContract.Presenter presenter;
    private CardOrderDetailWo.OrderBean order;

    private ToastDialog topLeftBackPressConfirmDialog = null;
    private ToastDialog deleteConfirmDialog = null;
    private ToastDialog payConfirmDialog = null;
    private ToastDialog offlinePayConfirmDialog = null;

    private Map<String, String> alipayParams;

    public static void startForResult(Activity activity, String fromActiviyName, Integer orderId, int requestCode){
        Intent intent = new Intent(activity, MyOrderDetailActivity.class);
        intent.putExtra(INTENT_KEY_FROM_ACTIVITY_NAME, fromActiviyName);
        intent.putExtra(INTENT_KEY_ORDER_ID, orderId);
        activity.startActivityForResult(intent, requestCode);

    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_my_order_detail;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbarMenuRight("订单详情", true, R.drawable.ic_alter_delete, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDeleteConfirmDialog();
            }
        });
        hideToolbarMenuRight();

        String activityName = getIntent().getStringExtra(INTENT_KEY_FROM_ACTIVITY_NAME);
        if (activityName.equals("MyRechargeActivity")){//1-代表来自国方购卡页面
            fromActivityStatus = 1;
        } else if (activityName.equals("MyOrderActivity")){//2-代表来自订单列表
            fromActivityStatus = 2;
        }
        orderId = getIntent().getIntExtra(INTENT_KEY_ORDER_ID, -1);

        presenter = new MyPresenter(this);
        presenter.addOrderDetailView(this);
        presenter.postCardOrderDetail(REQUEST_ACTION_POST_CARD_ORDER_DETAIL, orderId);

    }

    @Override
    protected void onTopLeftBackPressListener(View v) {
        if (fromActivityStatus == 1){
            showTopLeftBackPressConfirmDialog();
        } else {
            MyOrderDetailActivity.this.finish();
        }
    }

    private void showTopLeftBackPressConfirmDialog(){
        if (topLeftBackPressConfirmDialog == null){
            topLeftBackPressConfirmDialog = new ToastDialog(MyOrderDetailActivity.this, true, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyOrderDetailActivity.this.finish();
                }
            });
        }
        topLeftBackPressConfirmDialog.setTvContent("您将放弃此次支付操作。您可以在我的订单处继续该订单操作");
        topLeftBackPressConfirmDialog.show();
    }

    private void showDeleteConfirmDialog(){
        if (deleteConfirmDialog == null){
            deleteConfirmDialog = new ToastDialog(MyOrderDetailActivity.this, true, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    presenter.postDeleteOrder(REQUEST_ACTION_POST_DELETE_ORDER, orderId);
                    dialog.dismiss();
                }
            });
        }
        deleteConfirmDialog.setTvContent("是否确认删除该订单");
        deleteConfirmDialog.show();
    }


    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        showPayOfflineConfirmDialog();
    }

    private void showPayOfflineConfirmDialog(){
        final int payWay = order.getPayWay();
        if (payConfirmDialog == null){
            payConfirmDialog = new ToastDialog(MyOrderDetailActivity.this, true, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (payWay == 1){//线下支付
                        //点击确认，弹框提示用户，此时并没有更改订单状体，具体你看 ios 的处理，这里没有接口吊起，如果你在去订单处理那，
                        // 在选择该订单，在此选择 支付，那么此时，将吊起 接口 2.6.3  更改 线下支付 订单状态。
                        if (fromActivityStatus == 1){
                            showOfflinePayConfirmDialog();
                        } else if (fromActivityStatus == 2){
                            presenter.postUpdateOfflinePayStatus(REQUEST_ACTION_POST_UPDATE_OFFLINE_PAY_STATUS, orderId);
                        }
                    } else if (payWay == 3){//支付宝支付
                        String appid = "2088721305058421";
                        String out_trade_no = String.valueOf(orderId);
                        String money = "0.01";
                        String body = "国方支付body";
                        String subject = "国方支付subject";
                        String notify_url = "http://shjs.iketong.cn/Alipay/AlipayResult.ashx";
                        AliPayModel aliPayModel = new AliPayModel(out_trade_no, money, body, subject, notify_url);
                        alipayParams = AliPayOrderInfoUtil.getParams(appid, aliPayModel);
                        String authInfo = AliPayOrderInfoUtil.getAuthInfo(alipayParams);//准备发送给服务端进行Rsa2加密
                        presenter.postAlipaySign(REQUEST_ACTION_POST_ALIPAY_SIGN, authInfo);
                    }
                }
            });
        }
        if (fromActivityStatus == 1){
            payConfirmDialog.setTvContent("是否进入支付阶段");
        } else if (fromActivityStatus == 2){
            if (payWay == 1){
                payConfirmDialog.setTvContent("该操作代表你已汇款于国方。选择确认后，将无法更改");
            } else if (payWay == 3){
                payConfirmDialog.setTvContent("是否进入支付阶段");
            }
        }

        payConfirmDialog.show();
    }

    private void showOfflinePayConfirmDialog(){
        if (offlinePayConfirmDialog == null){
            offlinePayConfirmDialog = new ToastDialog(MyOrderDetailActivity.this, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MyOrderDetailActivity.this.finish();
                }
            });
        }
        offlinePayConfirmDialog.setTvContent("    尊贵的用户您好，你的线下支付已申请，请您与我司工作人员沟通，汇款完成后，请前往我的订单处，完成支付确认。");
        offlinePayConfirmDialog.show();
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(int requestAction, CardOrderDetailWo cardOrderDetailWo) {
        if (cardOrderDetailWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            initDetailView(cardOrderDetailWo);
        } else {
            toastMsg("获取数据失败");
        }

    }

    @Override
    public void responseSuccess(int requestAction, PaySignWo paySignWo) {
        if (paySignWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            AliPayTools.aliPay(MyOrderDetailActivity.this, alipayParams, paySignWo.getSign(), new onRequestListener() {
                @Override
                public void onSuccess(String s) {
                    LogUtils.d("支付宝支付结果："+s);
                    toastMsg("成功支付,开始改变支付状态。");
                    presenter.postUpdateOrderPayStatus(REQUEST_ACTION_POST_UPDATE_ORDER_PAY_STATUS, orderId);
                }

                @Override
                public void onError(String s) {
                    toastMsg("支付失败");
                }
            });
        } else {
            toastMsg("获取加密数据失败");
        }
    }

    @Override
    public void responseSuccess(int requestAction, StatusWo statusWo) {
        if (requestAction == REQUEST_ACTION_POST_DELETE_ORDER){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                setResultToOrderList(true);
            } else {
                toastMsg("删除失败："+statusWo.getErr());
            }
        } else if (requestAction == REQUEST_ACTION_POST_UPDATE_OFFLINE_PAY_STATUS){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                btnSubmit.setBackgroundColor(ContextCompat.getColor(MyOrderDetailActivity.this, R.color.gray));
                btnSubmit.setClickable(false);
                btnSubmit.setText("用户已付款，请通知我司工作人员跟进订单");
                setResultToOrderList(false);
            } else {
                toastMsg("提交失败");
            }
        } else if (requestAction == REQUEST_ACTION_POST_UPDATE_ORDER_PAY_STATUS){
            if (statusWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
                toastMsg("完成支付");
                setResultToOrderList(true);
            } else {
                toastMsg("改变支付状态失败");
            }

        }
    }

    private void initDetailView(CardOrderDetailWo  cardOrderDetailWo){
        CardOrderDetailWo.UserCardBean userCard  = cardOrderDetailWo.getUserCard();
        if (userCard != null){
            llUserCard.setVisibility(View.VISIBLE);
            tvUserCardNameAboveImage.setText(userCard.getName());
            tvUserCardName.setText("国方卡-"+userCard.getName());
            tvUserCardPriceAboveImage.setText("¥"+userCard.getPrice());
            tvUserCardPrice.setText(HtmlUtil.fromHtml("<font color=\"#000000\">¥"+userCard.getPrice()+"元<br /></font>" +
                    "<font color=\"#FF0006\">¥"+userCard.getPrice()+"</font>元"));
        }

        List<CardOrderDetailWo.AttachedCardBean> attachedCardList = cardOrderDetailWo.getAttachedCard();
        if (attachedCardList != null){
            if (attachedCardList.size() > 0){
                CardOrderDetailWo.AttachedCardBean attachedCard = attachedCardList.get(0);
                llAttachedCard.setVisibility(View.VISIBLE);
                tvAttachedCardNameAboveImage.setText(attachedCard.getName());
                tvAttachedCardName.setText("国方卡-"+attachedCard.getName());
                tvAttachedCardPriceAboveImage.setText("¥"+attachedCard.getPrice());
                tvAttachedCardPrice.setText(HtmlUtil.fromHtml("<font color=\"#000000\">¥"+attachedCard.getPrice()+"元<br /></font>" +
                        "<font color=\"#FF0006\">¥"+attachedCard.getPrice()+"</font>元"));
            }
        }

        List<CardOrderDetailWo.CouponCardBean> couponCardList = cardOrderDetailWo.getCouponCard();
        if (couponCardList != null){
            if (couponCardList.size() > 0){
                CardOrderDetailWo.CouponCardBean couponCard = couponCardList.get(0);
                llCouponCard.setVisibility(View.VISIBLE);
                tvCouponCardNameAboveImage.setText(couponCard.getName());
                tvCouponCardRate.setText("折让"+couponCard.getDiscountRate()+"%");
            }
        }

        order = cardOrderDetailWo.getOrder();
        tvAllSumPrice.setText("¥"+cardOrderDetailWo.getSumPrice()+"元");
        if (order != null) {
            tvMinusSumPrice.setText("-¥" + (cardOrderDetailWo.getSumPrice() - order.getSumPrice()) + "元");
            tvActualSumPrice.setText("实付款：¥" + order.getSumPrice() + "元");

            tvOrderCode.setText("" + order.getOrderCode());
            tvOrderTime.setText("" + order.getOrderTime());
//            int currency = order.getOrderCode()

            int payWay = order.getPayWay();
            if (payWay == 1){//线下支付
                tvPayWay.setText("支付方式：线下支付");
                boolean offlinePayStatus = order.isOfflinePayStatus();
                if (offlinePayStatus){
                    btnSubmit.setBackgroundColor(ContextCompat.getColor(MyOrderDetailActivity.this, R.color.gray));
                    btnSubmit.setClickable(false);
                    btnSubmit.setText("用户已付款，请通知我司工作人员跟进订单");
                } else {
                    btnSubmit.setText("汇款确认");
                }

            } else if (payWay == 3){//支付宝支付
                tvPayWay.setText("支付方式：");
                Drawable rightDrawable = ContextCompat.getDrawable(MyOrderDetailActivity.this, R.drawable.ic_alipa_pressed);
                rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
                tvPayWay.setCompoundDrawables(null, null, rightDrawable, null);
                btnSubmit.setText("支付");
            }

            boolean payStatus = order.isPayStatus();
            if (payStatus){
                btnSubmit.setVisibility(View.GONE);
            } else {
                btnSubmit.setVisibility(View.VISIBLE);
                if (fromActivityStatus == 2){//来自订单列表
                    if (payWay == 1) {//线下支付
                        boolean offlinePayStatus = order.isOfflinePayStatus();
                        if (!offlinePayStatus){//还没做汇款确认的
                            showToolbarMenuRight();
                        }
                    } else {
                        showToolbarMenuRight();
                    }

                }
            }
        }

        String offlinePay = cardOrderDetailWo.getOfflinePay();
        if (!TextUtils.isEmpty(offlinePay)){
            tvOfflinePay.setVisibility(View.VISIBLE);
            tvOfflinePay.setText(cardOrderDetailWo.getOfflinePay());
        }

    }

    private void setResultToOrderList(boolean isFinish){
        Intent intent = getIntent();
        intent.putExtra(INTENT_KEY_IS_NEED_REFLASH, true);
        setResult(RESULT_OK, intent);
        if (isFinish){
            MyOrderDetailActivity.this.finish();
        }
    }
}
